package cc.plumgo.ss.core;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import cc.plumgo.j2me.utils.CustomCanvas;
import cc.plumgo.ss.ui.UIEngine;
import cc.plumgo.ss.yo.YoEngine;

public class MainCanvas extends CustomCanvas implements GameListener {

	private UIEngine uiEngine;
	private YoEngine yoEngine;
	private Image bufImage;
	private Image outImage;
	public MainCanvas() {
		canvas = this;
		//state = GLB_UI;
		uiEngine = new UIEngine();
		uiEngine.setState(UIEngine.UI_POST);
		yoEngine = new YoEngine();
		bufImage = Image.createImage(getWidth(), getHeight());
		outImage = Image.createImage(getWidth(), getHeight());
		Console.getInstance().setGameListener(this);
		/*
		state = GLB_YO;
		restart();
		launch(YoEngine.SCENE_PLAYGRND);
		state = GLB_YO;
		showPage(UIEngine.UI_FOOT);
		showPage(UIEngine.UI_OVER);
		*/
		start();
	}

	public void process() {
		int key = getKeyStates();
		Graphics g = getGraphics();
		Graphics bufg = bufImage.getGraphics();
		bufg.setColor(0x00000000);
		bufg.fillRect(0, 0, getWidth(), getHeight());
		switch (state) {
		case GLB_UI:
			uiEngine.process(key, bufg);
			break;
		case GLB_YO: {
			yoEngine.process(bufg);
		}
		}
		g.drawImage(bufImage, 0, 0, 0);
		outImage.getGraphics().drawImage(bufImage, 0, 0, 0);
		flushGraphics();
	}
	
	public void yoEngineInput(int keyCode) {
		yoEngine.input(keyCode);
	}
	
	protected void keyPressed(int keyCode) {
		super.keyPressed(keyCode);
		yoEngineInput(keyCode);
	}

	protected void keyRepeated(int keyCode) {
		super.keyRepeated(keyCode);
		yoEngineInput(keyCode);
	}

	public void restart() {
		state = GLB_YO;
		yoEngine.reset(YoEngine.SCENE_CORRIDOR);
	}

	public void resume() {
		
	}

	public void showPage(int type) {
		state = GLB_UI;
		uiEngine.setState(type);
	}

	public void launch(int sindex) {
		state = GLB_YO;
		yoEngine.reset(sindex);
	}

	public void nextLevel() {
		state = GLB_YO;
		int tmp = yoEngine.getSceneIndex() + 1;
		if (tmp < YoEngine.SCENE_NUM) {
			yoEngine.reset(tmp);
		} else {
			showPage(UIEngine.UI_FOOT);
		}
	}

	public void recordScreen() {
		Image image = Image.createImage(outImage);
		Console.getInstance().setScreen(image);
	}
}
